package com.langyue.lintcode.main;

import java.time.LocalDate;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author: wanglang
 * @CreateTime: 2022/1/24
 * @Company:
 */
public class ThreadWeekDays {
    static String[] day = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
    static Map<String, String> map = new Hashtable<>();
    static long time;
    static Thread[] getWeekDay() throws Exception {
        time=System.currentTimeMillis();
        Thread[] weekDay = new Thread[7];
        // write your code here
        //七个线程，每个线程计算单独周日期的年月日期
        for (int i = 0; i < 7; i++) {
            int finalI = i;
            weekDay[i] = new Thread(() -> {
                //因为期望答案 是2021-10-8开始计算，所以这里是2020-10-8
                // 2021-10-8 当天是 周五
                addKV(getDate("2021-10-08", finalI), day[(finalI + 5) % 7]);
            });
        }

        return weekDay;
    }
    /**
     *@param day 周日期
     */
    static void addKV(String startTime, String day) {
        // 添加循环创建多线程，缩短运行时间
        for (int i = 0; i < 2; i++) {
            final int index = i;
            new Thread(() -> {
                String start = getDate(startTime, index * 500*7);
                for (int j = 0; j < 500; j++) {
                    map.put(start, day);
                    start = getDate(start, 7);
                }
            }).start();
        }

    }
    //手动计算日期
    /**
     *@param space 间隔天数
     */
    public static String getDate(String data, int space) {
        String[] datas = data.split("-");
        int y = Integer.parseInt(datas[0]);
        int m = Integer.parseInt(datas[1]);
        int d = Integer.parseInt(datas[2]);
        return getDate(y, m, d, space);
    }

    public static String getDate(int year, int moon, int day, int space) {

        int nd = day + space;
        boolean leapYear = year % 400 == 0 || (year % 100 != 0 && year % 4 == 0);
        int max = 31;
        switch (moon) {
            case 2:
                max = 28 + (leapYear ? 1 : 0);
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                max = 30;
                break;
        }
        if (nd > max) {
            moon++;
            if (moon > 12) {
                year++;
                moon = 1;
            }
            day = 1;
            space = nd - max - 1;
            return getDate(year, moon, day, space);
        }
        return year + "-" + moon + "-" + nd;
    }
}
